package Demo;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-07-30
 * Time: 22:33
 */
class MyTask implements Comparable<MyTask>{
    private long time;
    private Runnable command;
    public MyTask(Runnable command,long time) {
        this.time=System.currentTimeMillis()+time;
        this.command=command;
    }
    public void run() {
        command.run();
    }
    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer {
    private Object o = new Object();
    PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<MyTask>();
    public void schedule(Runnable command,long after) {
        MyTask t = new MyTask(command,after);
        synchronized (o) {
            queue.put(t);
            o.notifyAll();
        }
    }
    public MyTimer() {
        Thread t = new Thread(() -> {
            while(true) {
                try {
                    synchronized (o) {
                        if (queue.isEmpty()) {
                            o.wait();
                        }
                        MyTask myTask = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (curTime < myTask.getTime()) {
                            //时间没到，塞回去
                            queue.put(myTask);
                            o.wait(myTask.getTime() - curTime);
                        } else {
                            //时间到了,执行
                            myTask.run();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class demo2 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(1111);
            }
        },1000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(2222);
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(3333);
            }
        },3000);
    }
}